import wsgiref.handlers
import sys
import os
import string
import codecs
import geohash
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging

DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import urlfetch
from datetime import datetime, timedelta
from django.core import serializers
from django.http import HttpResponsePermanentRedirect
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.api import images 
from google.appengine.ext.db import GqlQuery
from models import *
from utilities import *



class FilmAction(webapp.RequestHandler):
  def get(self,filmid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     film=Film.get(filmid)
     film.delete()
     self.redirect("/admin/films/", False)
     return 1
   elif action=='edit':
     film=Film.get(filmid)
     querygenre = Genre.all()
     genres = querygenre.fetch(100)
     querypeople = Person.all()
     querypeople.order('url')
     people = querypeople.fetch(500)
     directors = []
     actors = []
     for person in people:
       if person.role.url == 'director':
         directors.append(person)
       elif person.role.url == 'actor-director':
         directors.append(person)
         actors.append(person)
       elif person.role.url == 'actor':
         actors.append(person)
     personxfilmquery = PersonxFilm.all()
     personxfilmquery.filter('film = ', film)
     personxfilms = personxfilmquery.fetch(500)
     for personxfilm in personxfilms:
       for actor in actors:
         if actor.key()==personxfilm.person.key():
           actors.remove(actor)

     template_values = {
       'film': film,
       'genres': genres,
       'actors': actors,
       'directors': directors,
       'personxfilms': personxfilms,
       'path': "/admin/films/"+filmid+"/save/",
     }
   elif action=='new':
     querygenre = Genre.all()
     genres = querygenre.fetch(500)
     querypeople = Person.all()
     querypeople.order('url')
     people = querypeople.fetch(500)
     directors = []
     actors = []
     for person in people:
       if person.role.url == 'director':
         directors.append(person)
       elif person.role.url == 'actor-director':
         directors.append(person)
         actors.append(person)
       elif person.role.url == 'actor':
         actors.append(person)
     template_values = {
       'genres': genres,
       'actors': actors,
       'directors': directors,
       'path': "/admin/films//save/",
     }
   path = os.path.join(os.path.dirname(__file__), 'admin/film.html')
   self.response.out.write(template.render(path, template_values))
     
  def post(self,filmid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':
     if filmid!='':
       film=Film.get(filmid)
       autonumeric = -1
     else:
       film = Film()
       config=Configuration.get('agpoZWFkZXJsaW5lchULEg1Db25maWd1cmF0aW9uGIftCQw')
       autonumeric=int(config.value)
       config.autonumeric = str(autonumeric+1)
       config.put()

     if self.request.get("save")!='':
       originalname = self.request.get("originalname")
       name = self.request.get("name")
       url = self.request.get("url")
       director = Person.get(self.request.get("director"))
       year = int(self.request.get("year"))
       description = self.request.get("description")
       genre = Genre.get(self.request.get("genre"))
       film.originalname = originalname
       film.name = name
       film.url = url
       film.year = year
       film.genre = genre
       film.director = director
       film.customuser = customuser
       film.userurl = customuser.url
       film.description = description
       
       film.customuser = customuser
       if autonumeric!= -1:
         film.autonumeric = autonumeric
       film.put()

       if self.request.get("cast")!="unchanged":
       	querypersonxfilm=PersonxFilm.all()
       	querypersonxfilm.filter("film = ",film)
       	personxfilms = querypersonxfilm.fetch(50)
       	for personxfilm in personxfilms:
       		personxfilm.delete()
       	strmypeople=self.request.get("cast")
       	if strmypeople!="":
       		mypeople=str(strmypeople).split(',')
       		i=0
       		while i<len(mypeople):
       			personxfilm=PersonxFilm()
       			personxfilm.person=Person.get(mypeople[i])
       			personxfilm.film=film
       			personxfilm.put()
       			i+=1

     self.redirect("/admin/films/", True)



class FilmsList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   queryfilms = Film.all()
   queryfilms.filter('customuser = ', customuser)
   queryfilms.order('name')
   films = queryfilms.fetch(500)
   template_values = {
     'customuser': customuser,
     'films': films
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/films.html')
   self.response.out.write(template.render(path, template_values))



class GenresList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   querygenres = Genre.all()
   querygenres.order('name')
   genres = querygenres.fetch(500)
   template_values = {
     'genres': genres,
     'customuser': customuser
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/genres.html')
   self.response.out.write(template.render(path, template_values))



class GenreAction(webapp.RequestHandler):
  def get(self,genreid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     genre=Genre.get(genreid)
     genre.delete()
     self.redirect("/admin/genres/", False)
     return 1
   elif action=='edit':
     genre=Genre.get(genreid)

     template_values = {
       'genre': genre,
       'path': "/admin/genres/"+genreid+"/save/",
     }
   elif action=='new':
     template_values = {
       'path': "/admin/genres//save/",
     }
   path = os.path.join(os.path.dirname(__file__), 'admin/genre.html')
   self.response.out.write(template.render(path, template_values))
     
  def post(self,genreid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':
     if genreid!='':
       genre=Genre.get(genreid)
     else:
       genre = Genre()

     if self.request.get("save")!='':
       name = self.request.get("name")
       url = self.request.get("url")
       description = self.request.get("description")
       genre.name = name
       genre.url = url
       genre.description = description
       
       genre.put()

     self.redirect("/admin/genres/", True)



class Index(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   self.redirect("/admin/films/", True)



class PeopleList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   querypeople = Person.all()
   querypeople.order('name')
   people = querypeople.fetch(1000)
   template_values = {
     'people': people
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/people.html')
   self.response.out.write(template.render(path, template_values))



class PersonAction(webapp.RequestHandler):
  def get(self,personid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     person=Person.get(personid)
     person.delete()
     self.redirect("/admin/people/", False)
     return 1
   elif action=='edit':
     person = Person.get(personid)
     queryroles = Role.all()
     roles = queryroles.fetch(100)
     template_values = {
       'person': person,
       'roles': roles,
       'path': "/admin/people/"+personid+"/save/",
     }
   elif action=='new':
     queryroles = Role.all()
     roles = queryroles.fetch(100)
     template_values = {
       'roles': roles,
       'path': "/admin/people//save/",
     }
   path = os.path.join(os.path.dirname(__file__), 'admin/person.html')
   self.response.out.write(template.render(path, template_values))
     
  def post(self,personid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='save':
     if personid!='':
       person=Person.get(personid)
     else:
       person = Person()

     if self.request.get("save")!='':
       name = self.request.get("name")
       url = self.request.get("url")
       description = self.request.get("description")
       role = Role.get(self.request.get("role"))
       person.name = name
       person.url = url
       person.role = role
       person.description = description
       person.put()

     self.redirect("/admin/people/", True)



class UserAction(webapp.RequestHandler):
  def get(self,customuserid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     customuser=CustomUser.get(customuserid)
     customuser.delete()
     self.redirect("/admin/users/", True)
     return 1
   elif action=='new':
     template_values = {
       'path': "/admin/users//save/",
     }
   elif action=='edit':
     theuser=CustomUser.get(customuserid)
     template_values = {
       'user': theuser,
       'customuser': customuser,
       'path': "/admin/users/"+str(theuser.key())+"/save/",
     }

   path = os.path.join(os.path.dirname(__file__), 'admin/user.html')
   self.response.out.write(template.render(path, template_values))


  def post(self,customuserid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if  action=="save":
     if self.request.get("save")!="":
       if customuserid!='':
         customuser=CustomUser.get(customuserid)
       else:
         customuser=CustomUser()
       error=False
       message="error"
     #if self.request.get("author")=="":
      # error=True
       #message+="You must indicate your name<br/>"
     #if self.request.get("email")=="":
       #error=True
       #message+="You must indicate your email<br/>"
     #if self.request.get("email").find("@")==-1 :
       #error=True
       #message+="You must indicate a valid email<br/>"
     #if self.request.get("message")=="":
       #error=True
       #message+="You must write a comment"

     if error :
        template_values = {
        		'customuser': customuser,
        		'path': "/admin/users/"+str(customuser.key())+"/save/",
        }

        path = os.path.join(os.path.dirname(__file__), 'admin/user.html')
        self.response.out.write(template.render(path, template_values))
     else:
       name=self.request.get("name")
       url=self.request.get("url")
       role=self.request.get("role")
       email=self.request.get("email")
       customuser.name = name
       customuser.role = role
       customuser.url = url
       customuser.user = users.User(email = email)
       customuser.put()
       template_values = {
       	'customuser': customuser,
       	'path': "/admin/users/"+str(customuser.key())+"/save/",
       }

       self.redirect("/admin/users/", True)



class UsersList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   queryusers=CustomUser.all()
   queryusers.order("name")
   customusers=queryusers.fetch(50)
   template_values = {
     'customuser': customuser,
     'customusers': customusers,
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/users.html')
   self.response.out.write(template.render(path, template_values))
  def post(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   searchtext=self.request.get("busqueda")
   if self.request.get("page")=='':
   	page=0
   else:
   	page=int(self.request.get("page"))

   offset=page*20
   queryusers=CustomUser.all().search(searchtext)
   queryusers.order('name')     
   customusers=queryusers.fetch(50,offset)

   template_values = {
     'customusers': customusers,
     'page': page,
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/users.html')
   self.response.out.write(template.render(path, template_values))



def main():
  application = webapp.WSGIApplication([('/admin/', Index),
                                        ('/admin/films/(.*)/(edit)/', FilmAction),
                                        ('/admin/films/(.*)/(new)/', FilmAction),
                                        ('/admin/films/(.*)/(save)/', FilmAction),
                                        ('/admin/films/(.*)/(delete)/', FilmAction),
                                        ('/admin/people/(.*)/(edit)/', PersonAction),
                                        ('/admin/people/(.*)/(new)/', PersonAction),
                                        ('/admin/people/(.*)/(save)/', PersonAction),
                                        ('/admin/people/(.*)/(delete)/', PersonAction),
                                        ('/admin/users/(.*)/(edit)/', UserAction),
                                        ('/admin/users/(.*)/(new)/', UserAction),
                                        ('/admin/users/(.*)/(save)/', UserAction),
                                        ('/admin/users/(.*)/(delete)/', UserAction),
                                        ('/admin/genres/(.*)/(edit)/', GenreAction),
                                        ('/admin/genres/(.*)/(new)/', GenreAction),
                                        ('/admin/genres/(.*)/(save)/', GenreAction),
                                        ('/admin/genres/(.*)/(delete)/', GenreAction),
                                        ('/admin/users/', UsersList),
                                        ('/admin/films/', FilmsList),
                                        ('/admin/genres/', GenresList),
                                        ('/admin/people/', PeopleList),
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
